package com.zyht.wechat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wx.core.process.JEEWeiXinX509TrustManager;
import com.wx.core.process.WxApi;

@Service
public class AccessTokenVisitorImpl implements AccessTokenVisitor{

	@Resource
	private RedisAccessTokenVistor redisAccessTokenVistor;

	public String getTokenSequence(String wxid,String appId,String appSecret){

		String accessToken = redisAccessTokenVistor.getTokenSequence(wxid);
		if(null == accessToken){
			synchronized(this){
				accessToken = redisAccessTokenVistor.getTokenSequence(wxid);
				if(null == accessToken){
					String tockenUrl = WxApi.getTokenUrl(appId,appSecret);
					AccessToken token = getAccessTokenByHttp(tockenUrl);
					if(null!=token){
						this.redisAccessTokenVistor.persist(wxid, token);
						accessToken = token.getAccessToken();
					}
				}
			}
		}
		return accessToken;
	}

	private final AccessToken getAccessTokenByHttp(String urlString){
		TrustManager[] tm = { new JEEWeiXinX509TrustManager() };
		StringBuffer buffer = new StringBuffer();
		try{
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(urlString);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("GET");
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
		} catch (KeyManagementException | NoSuchAlgorithmException | NoSuchProviderException
			| IOException e){
			e.printStackTrace();
			return null;
		}
		JSONObject jsonObj = JSONObject.parseObject(buffer.toString());
		return JSON.toJavaObject(jsonObj,AccessToken.class);
	}
}
